<?php

namespace app\api\controller\v1;

use app\api\model\User as UserModel;
use app\common\controller\BaseController;
use app\api\model\Course as CourseModel;
use app\api\model\TeacherBusy as TeacherBusyModel;
use app\api\service\CourseRemindService;
use app\api\validate\ReserveCourseValidate;
use app\common\service\AlibabaCloudService;
use app\common\service\EasyWechatService;
use think\Db;
use app\api\model\CourseOrder as CourseOrderModel;
use app\api\model\Teacher as TeacherModel;
use app\api\model\TeacherMoneyLog as TeacherMoneyLogModel;
use think\Log;

/**
 * 课表
 */
class Course extends BaseController
{
    protected $noNeedLogin = ['index'];


   /**
    * 课表
    */
   public function index()
   {
       $status = $this->request->get('status');
       $size = $this->request->get('size');
       $page = $this->request->get('page');
       $userId = $this->userId;
       if ($status == 2) {
           $courses = CourseModel::waitCourse($userId);
           if ($page > 1) {
               $courses['course'] = [];
               $courses['total'] = 0;
           }
       } else {
           $courses = CourseModel::getByUserId($userId, [$this->status($status)], $size);
       }
       $courses['total'] ? $this->success('', $courses) : $this->notFoundData();


   }

    /**
     * 课表状态
     * @param $str
     * @return int
     */
   private function status($str)
   {
       $status = -1;
       switch ($str) {
           //待上课
           case 1:
               $status = 3;
               break;
           //待预约
           case 2:
               $status = 2;
               break;
           //往期
           case 3:
               $status = 4;
               break;
       }
       return $status;
   }

   /**
    * 课表详情
    */
   public function read()
   {
       $courseId = $this->notEmpty('course_id');
       $course = CourseModel::getByCourseId($courseId);
       $this->success('', compact('course'));
   }

   /**
    * 完成课程
    */
   public function finish()
   {
       $courseId = $this->notEmpty('course_id');
       $course = CourseModel::find($courseId);
       if (!$course) {
           $this->errorMsg(14000);
       }
       if ($course->status != 3) {
           $this->errorMsg(14002);
       }
       Db::startTrans();
       try {
           $course->status = 4;
           $course->save();
           //是否全部完成
           $courseCount = CourseModel::getCourseOrderCount($course->course_order_id, 4);
           $courseOrder = CourseOrderModel::find($course->course_order_id);
           if ($courseOrder && $courseCount == $courseOrder->num) {
               //更新订单完成
               $courseOrder->status = 3;
               $courseOrder->save();
               //教师
               $teacher = TeacherModel::find($courseOrder->teacher_id);
               if ($teacher) {
                   //记录教师账号明细
                   TeacherMoneyLogModel::add($teacher, $courseOrder->total_price, 1, $courseOrder->course_order_id);
                   //教师获得课程费
                   $teacher->setInc('money', $courseOrder->total_price);
               }
           }
           //课程提醒
           CourseRemindService::courseRemind($course->course_id, 2, true);

           Db::commit();
       } catch (\Exception $e) {
           Db::rollback();
       }
       isset($e) ? $e->getMessage() : $this->success('', ['course_id' => $course->course_id]);
   }

   /**
    * 预约课表
    */
   public function reservation(ReserveCourseValidate $reserveCourseValidate)
   {
       $this->isPost();
       $data = $this->request->post();
       $this->paramValidate($reserveCourseValidate, $data);
       $course = CourseModel::find($data['course_id']);
       if (!$course) {
           $this->errorMsg(14000);
       }
       if ($course->status != 2) {
           $this->errorMsg(14001);
       }
       $minIndex = CourseModel::getMinIndex($course->course_order_id);
       if ($course->index > $minIndex) {
           $this->errorMsg(14003);
       }
       $user = UserModel::find($course->user_id);
       if (!$user) {
           $this->errorMsg(9996);
       }
       $teacher = TeacherModel::find($course->teacher_id);
       if (!$teacher) {
           $this->errorMsg(20000);
       }
       $data['time'] = reserveTime($data['time']);
       //验证时间段是否可预约
       TeacherBusyModel::isBuy($course->teacher_course_id, $data['date'], $data['time']);
       $date = date('Y-m-d', strtotime($data['date']));
       if ($course->date == $date && $course->time == $data['time']) {
           $this->success('', ['course_id' => $course->course_id]);
       }
       Db::startTrans();
       try {
           //预约课程
           $course->date = $date;
           $course->week = getWeek($data['date']);
           $course->time = $data['time'];
           $course->status = 3;
           $course->save();
           //课程提醒
           CourseRemindService::courseRemind($course->course_id, 3);

           Db::commit();
       } catch (\Exception $e) {
           Db::rollback();
       }
       if (isset($e)) {
           $this->forbidden();
       }
       //订阅消息
       $time = str_replace('-', '~', $course->time);
       $this->subscribeData($user->wxapp_openid, $teacher->nickname, $course->date.' '.$time);
       //发送老师短信消息
       $params = [
           'name' => $user->nickname,
           'datetime' => date('m-d', strtotime($data['date'])).' '.$course->time
       ];
       AlibabaCloudService::sendSms($teacher->phone, 'SMS_200175451', json_encode($params));
       $this->success('', ['course_id' => $course->course_id]);
   }

    /**
     * 订阅数据
     */
    private function subscribeData($openid, $teacherName, $time)
    {
        $data = [
            'template_id' => config('wechat.template')['course_success'],
            'touser' => $openid,
            'page' => '',
            'data' => [
                'name1' => [
                    'value' => $teacherName
                ],
                'date3' => [
                    'value' => $time
                ]
            ]
        ];
        $easywechatService = new EasyWechatService();
        return $easywechatService->send($data);
    }

}
